package com.liyi.letter.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyi.letter.system.entity.Department;
import com.liyi.letter.system.entity.EmployeeRole;
import com.liyi.letter.system.entity.Role;
import com.liyi.letter.system.mapper.RoleMapper;
import com.liyi.letter.system.service.EmployeeRoleService;
import com.liyi.letter.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author Administrator
 * @description 针对表【role】的数据库操作Service实现
 * @createDate 2023-06-06 10:13:35
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Autowired
    private EmployeeRoleService employeeRoleService;

    @Override
    public List<Role> getAll() {
        return  baseMapper.selectList(null);
    }

    @Override
    public boolean deleteById(Long id) {
        Role role = baseMapper.selectById(id);
        QueryWrapper<EmployeeRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", role.getName());
        EmployeeRole employeeRole = new EmployeeRole();
        employeeRole.setRoleName("");
        employeeRoleService.update(employeeRole,queryWrapper);
        int i = baseMapper.deleteById(id);
        if (i == 1) {
            return true;
        }
        return false;
    }

    @Override
    public Page<Role> MyPage(Integer page, Integer pageSize, String name) {
        Page<Role> iPage = new Page<>(page, pageSize);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        baseMapper.selectPage(iPage, queryWrapper);
        iPage.getRecords().forEach(role -> {
            QueryWrapper<EmployeeRole> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("role_id",role.getId());
            Integer count = employeeRoleService.count(queryWrapper1);
            role.setRoleNum(count);
        });
        return iPage;
    }

    @Override
    public boolean updatedRole(Role role) {
        Role role1 = baseMapper.selectById(role.getId());
        QueryWrapper<EmployeeRole> queryWrapper = new QueryWrapper<>();
        EmployeeRole employeeRole = new EmployeeRole();
        employeeRole.setRoleName(role.getName());
        queryWrapper.eq("role_name", role1.getName());
        employeeRoleService.update(employeeRole, queryWrapper);
        baseMapper.updateById(role);
        return true;
    }
}
